<%@page import="io.github.ilkgunel.pojo.Record"%>
<%@ page import="java.util.Iterator" %>
<%@ page import="io.github.ilkgunel.pojo.Student" %>
<%@ page import="java.util.List" %>
<%@ page import="io.github.ilkgunel.dao.test2_1" %>
<%@ page import="io.github.ilkgunel.dao.test2_2" %>
<%@ page import="io.github.ilkgunel.dao.test2_3" %>
<%@ page import="io.github.ilkgunel.pojo.Teacher" %>
<%@ page import="io.github.ilkgunel.dao.teacherfind" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>



<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
    <link rel="shortcut icon" href="favicon.ico"> <link href="css/bootstrap.min.css?v=3.3.6" rel="stylesheet">
    <link href="css/font-awesome.css?v=4.4.0" rel="stylesheet">
    <link href="css/animate.css" rel="stylesheet">
    <link href="css/plugins/codemirror/codemirror.css" rel="stylesheet">
    <link href="css/plugins/codemirror/ambiance.css" rel="stylesheet">
    <link href="css/style.css?v=4.1.0" rel="stylesheet">
    <link href="css/plugins/iCheck/custom.css" rel="stylesheet">

</head>

<body>
<%
    List<Teacher> list = null;
    teacherfind dao=new teacherfind();
    list=dao.find();
    if(list==null){
%>
 <script>
     alert("教师数量为0！！")
 </script>
<%
}
    String insertMessage=(String)request.getAttribute("insertMessage");
    request.setAttribute("insertMessage",null);
    if(insertMessage!=null&&insertMessage.length()>0)
    {%>
    <script>
        alert("<%=insertMessage%>")
    </script>

    <%}%>

<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-sm-12">
            <div class="ibox float-e-margins">
                <div class="ibox-title">
                    <h5>test3.2 为实验一建立的教师集合插入数据，可以在前端界面中录入数据之后保存，也可以导入Excel中的数据。</h5>

                </div>
                <div class="ibox-content">
                    <div class="text-center">
                        <a data-toggle="modal" class="btn btn-primary" href="#modal-form">添加</a>
                    </div>
                    <input class="btn btn-primary" style="visibility: hidden" type="file" id="excel-file">
                    <button class="btn btn-primary" onclick="document.getElementById('excel-file').click()">从Excel表格中导入添加</button>


                    <table class="table table-striped table-bordered table-hover dataTables-example">
                        <thead>
                        <tr>
                            <th>教师编号</th>
                            <th>姓名</th>
                            <th>性别</th>
                            <th>年龄</th>
                            <th>院系名称</th>

                        </tr>
                        </thead>
                        <tbody>
                        <%

                            Teacher teacher=null;
                            if(list!=null&&list.size()!=0){

                                for(int i=0;i<list.size();i++) {
                                    teacher= list.get(i);


                        %>
                        <tr class="gradeX">
                            <td><%=teacher.getTid()%>
                            <td><%=teacher.getName()%>
                            <td><%=teacher.getSex()%>
                            </td>
                            <td><%=teacher.getAge()%></td>

                            <td class="center"><%=teacher.getDname()%></td>



                        </tr>
                        <%}}
                        %>

                        </tbody>

                    </table>

                </div>
            </div>
        </div>
    </div>

</div>

<%--代码部分--%>
<div class="wrapper wrapper-content  animated fadeInRight">
    <div class="row">
        <div class="col-sm-6">
            <div class="ibox ">
                <div class="ibox-title">
                    <h5>实验关键代码</h5>
                </div>
                <div class="ibox-content">

                    <p class="m-b-lg">
                        <strong>operations  </strong>test3_2.java
                    </p>

                    <textarea id="code1">
@WebServlet(name = "test3_2", urlPatterns = {"/test3_2"})
public class test3_2 extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //processRequest(request, response);
        String insertMessage = "";

        String tid= request.getParameter("tid");
        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        int age = Integer.parseInt(request.getParameter("age"));
        String birthday = request.getParameter("birthday");
        String dname= request.getParameter("dname");
        String theclass= request.getParameter("class");

        AccessMongoDB accessMongoDB = new AccessMongoDB();

        try {
            accessMongoDB.getCollection("teacher").insertOne(
                    new Document()
                    .append("tid",tid )
                    .append("name", name)
                    .append("sex", sex)
                    .append("age",age)

                    .append("dname",dname)

            );
            insertMessage = "Record successfully inserted!";
            System.out.println(insertMessage);
        } catch (Exception e) {
            insertMessage = "An error occured while inserting data! Error is:"+e;
            System.out.println(insertMessage);
        }
        request.setAttribute("insertMessage", insertMessage);
        int index=request.getHeader("Referer").indexOf("test");
        RequestDispatcher dispatcher = request.getRequestDispatcher(request.getHeader("Referer").substring(index));
        dispatcher.forward(request, response);
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String insertMessage = "";
        request.setAttribute("insertMessage", insertMessage);
        int index=request.getHeader("Referer").indexOf("test");
        RequestDispatcher dispatcher = request.getRequestDispatcher(request.getHeader("Referer").substring(index));
        dispatcher.forward(request, response);
    }
}

</textarea>
                </div>
            </div>
        </div>

    </div>
</div>
<br>

<div id="modal-form" class="modal fade" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                <div class="row">
                    <div class="col-sm-6 b-r">
                        <h3 class="m-t-none m-b">添加教师</h3>
                        <form role="form" action="/web/test3_2" method="post">
                            <div class="form-group">
                                <label>教师编号：</label>
                                <input type="text" name="tid" placeholder="请输入教师编号" class="form-control">
                            </div>
                            <div class="form-group">
                                <label>姓名：</label>
                                <input type="text" name="name" placeholder="请输入姓名" class="form-control">
                            </div>
                            <div class="form-group">
                                <label>性别：</label>
                                <input type="text" name="sex" placeholder="请输入性别" class="form-control">
                            </div>
                            <div class="form-group">
                                <label>年龄：</label>
                                <input type="text" name="age" placeholder="请输入年龄" class="form-control">
                            </div>


                            <div class="form-group">
                                <label>学院：</label>
                                <input name="dname"  type="text" placeholder="请输入学院" class="form-control">
                            </div>

                            <button type="button" onclick="history.go(0) " style="margin-right: 82px;" class="btn btn-sm btn-primary pull-right m-t-n-xs" ><strong style="margin-right: 0px;">取消</strong>
                            </button>
                            <div>
                                <button style="margin-right: 178px;"  class="btn btn-sm btn-primary pull-right m-t-n-xs" type="submit"><strong>添加</strong>
                                </button>
                            </div>
                        </form>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>


<a href="<c:url value="dataInsert"></c:url>">添加</a>
<!-- 全局js -->
<script src="js/jquery.min.js?v=2.1.4"></script>
<script src="js/bootstrap.min.js?v=3.3.6"></script>

<!-- Peity -->
<script src="js/plugins/peity/jquery.peity.min.js"></script>

<!-- CodeMirror -->
<script src="js/plugins/codemirror/codemirror.js"></script>
<script src="js/plugins/codemirror/mode/javascript/javascript.js"></script>

<%----%>
<script src="js/plugins/jeditable/jquery.jeditable.js"></script>

<!-- Data Tables -->
<script src="js/plugins/dataTables/jquery.dataTables.js"></script>
<script src="js/plugins/dataTables/dataTables.bootstrap.js"></script>
<!-- 自定义js -->
<script src="js/content.js?v=1.0.0"></script>

<script>
    $(document).ready(function () {


        var editor_one = CodeMirror.fromTextArea(document.getElementById("code1"), {
            lineNumbers: true,
            matchBrackets: true,
            styleActiveLine: true,
            theme: "ambiance"
        });

        var editor_two = CodeMirror.fromTextArea(document.getElementById("code2"), {
            lineNumbers: true,
            matchBrackets: true,
            styleActiveLine: true
        });


        $('.dataTables-example').dataTable();

        /* Init DataTables */
        var oTable = $('#editable').dataTable();

        /* Apply the jEditable handlers to the table */
        oTable.$('td').editable('../example_ajax.php', {
            "callback": function (sValue, y) {
                var aPos = oTable.fnGetPosition(this);
                oTable.fnUpdate(sValue, aPos[0], aPos[1]);
            },
            "submitdata": function (value, settings) {
                return {
                    "row_id": this.parentNode.getAttribute('id'),
                    "column": oTable.fnGetPosition(this)[2]
                };
            },

            "width": "90%",
            "height": "100%"
        });

    });


    function fnClickAddRow() {
        $('#editable').dataTable().fnAddData([
            "Custom row",
            "New row",
            "New row",
            "New row",
            "New row"]);

    }

</script>

<!-- iCheck -->
<script src="js/plugins/iCheck/icheck.min.js"></script>
<script>
    $(document).ready(function () {
        $('.i-checks').iCheck({
            checkboxClass: 'icheckbox_square-green',
            radioClass: 'iradio_square-green',
        });
    });
</script>

<!-- layerDate plugin javascript -->
<script src="js/plugins/layer/laydate/laydate.js"></script>
<script>
    //外部js调用
    laydate({
        elem: '#hello', //目标元素。由于laydate.js封装了一个轻量级的选择器引擎，因此elem还允许你传入class、tag但必须按照这种方式 '#id .class'
        event: 'focus' //响应事件。如果没有传入event，则按照默认的click
    });

    //日期范围限制
    var start = {
        elem: '#start',
        format: 'YYYY/MM/DD hh:mm:ss',
        min: laydate.now(), //设定最小日期为当前日期
        max: '2099-06-16 23:59:59', //最大日期
        istime: true,
        istoday: false,
        choose: function (datas) {
            end.min = datas; //开始日选好后，重置结束日的最小日期
            end.start = datas //将结束日的初始值设定为开始日
        }
    };
    var end = {
        elem: '#end',
        format: 'YYYY/MM/DD hh:mm:ss',
        min: laydate.now(),
        max: '2099-06-16 23:59:59',
        istime: true,
        istoday: false,
        choose: function (datas) {
            start.max = datas; //结束日选好后，重置开始日的最大日期
        }
    };
    laydate(start);
    laydate(end);
</script>

<%--EXCEL表格插入--%>
<script src="http://www.jq22.com/jquery/jquery-1.10.2.js"></script>
<script type="text/javascript" src="xlsx.core.min.js"></script>

<script type="text/javascript">
    $('#excel-file').change(function(e) {
        var files = e.target.files;

        var fileReader = new FileReader();
        fileReader.onload = function(ev) {
            try {
                var data = ev.target.result,
                    workbook = XLSX.read(data, {
                        type: 'binary'
                    }), // 以二进制流方式读取得到整份excel表格对象
                    persons = []; // 存储获取到的数据
            } catch (e) {
                console.log('文件类型不正确');
                return;
            }

            // 表格的表格范围，可用于判断表头是否数量是否正确
            var fromTo = '';
            // 遍历每张表读取
            for (var sheet in workbook.Sheets) {
                if (workbook.Sheets.hasOwnProperty(sheet)) {
                    fromTo = workbook.Sheets[sheet]['!ref'];
                    console.log(fromTo);
                    persons = persons.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                    // break; // 如果只取第一张表，就取消注释这行
                }
            }

            console.log(persons);
            //清空表格
            $(".tablehead").html("");
            $(".tablebody").html("");
            for(var j=0;j<persons.length;j++){
                var arr=persons[j];
                if(j==0){
                    $(".tablehead").append("<tr class='exceltitle'></tr>");
                }
                $(".tablebody").append("<tr class='excelcontent'></tr>");
                for (var i in arr) {
                    //alert(i+"---"+arr[i]);
                    if(j==0){
                        $(".exceltitle").append("<th>"+i+"</th>");
                    }
                    $(".excelcontent").eq(j).append("<td>"+arr[i]+"</td>");
                }
            }

        };
        // 以二进制方式打开文件
        fileReader.readAsBinaryString(files[0]);
    });
</script>

</body>
</html>
